package com.company.client;

import com.company.common.FileMetaInfo;
import com.company.common.Message;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 连接服务端的线程管理类
 */
public class ConnSvrThdManage {
    private static final Map<String, ConnSvrThread> THREAD_MAP = new HashMap<>();

    public static ConnSvrThread get(String username) {
        return THREAD_MAP.get(username);
    }

    public static void add(String username, ConnSvrThread thread) {
        THREAD_MAP.put(username, thread);
    }

    public static void remove(String username) {
        THREAD_MAP.remove(username);
    }
}

class ConnSvrThread extends Thread {

    private Socket socket;

    public ConnSvrThread(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void run() {
        while (!socket.isClosed()) {
            try {
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) inputStream.readObject();
                switch (message.getType()) {
                    case RET_ONLINE_FRIENDS:
                        String[] content = (String[]) message.getContent();
                        for (String s : content) {
                            System.out.println("用户：" + s);
                        }
                        break;
                    case NORMAL_MSG:
                        String msg = (String) message.getContent();
                        System.out.println(message.getSender() + "对" + message.getReceiver() + "说：" + msg + " 时间：" + message.getTime());
                        break;
                    case GROUP_MSG:
                        String grpMsg = (String) message.getContent();
                        System.out.println(message.getSender() + "对大家说：" + grpMsg + " 时间：" + message.getTime());
                        break;
                    case FILE_MSG:
                        FileMetaInfo fileMsg = (FileMetaInfo) message.getContent();
                        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(fileMsg.getToPath()));) {
                            outputStream.write(fileMsg.getBytes());
                        }
                        System.out.println(message.getSender() + "给" + message.getReceiver() + "发送文件:" + fileMsg.getFromPath() + "到我的电脑目录：" + fileMsg.getToPath() + " 时间：" + message.getTime());
                        break;
                    case CLI_EXIT:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
